package com.example.cmliu.fragmentdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.fragment.app.FragmentTransaction;
import androidx.fragment.app.ListFragment;

public class MyListFragment extends ListFragment {

    int curCheckPosition = 0; // 当前选择的索引位置

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 为列表设置适配器
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_checked, Data.TITLES));

        if (savedInstanceState != null) {
            // 更新当前选择的索引位置
            curCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
        // 设置列表为单选模式
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        showDetails(curCheckPosition); // 显示详细内容

    }

    // 重写onSaveInstanceState()方法，保存当前选中的列表项的索引值
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("curChoice", curCheckPosition);
        super.onSaveInstanceState(outState);
    }

    // 重写onListItemClick()方法
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position); // 调用showDetails()方法显示详细内容
    }

    void showDetails(int index) {
        curCheckPosition = index; // 更新保存当前索引位置的变量的值为当前选中值

        getListView().setItemChecked(index, true); // 设置选中列表项为选中状态

        DetailFragment details = (DetailFragment) getFragmentManager()
                .findFragmentById(R.id.detail); // 获取用于显示详细内容的Fragment
        // 创建一个新的DetailFragment实例用于显示当前选择项对应的详细内容
        if (details == null || details.getShownIndex() != index) {
            details = DetailFragment.newInstance(index);

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.detail, details);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();
        }

    }

}
